package com.shuql.cloud.oauth2.config;

import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.IOException;

/**
 * @author ：shuquanliang
 * @date ：Created in 2020/4/23 10:50
 * @description：
 */
@Configuration
public class TokenConfig {

    private static final String SIGNING_KEY = "SIGNING_KEY";

    /**
     * JWT转换器
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //对称解密进行签名令牌，资源服务器也要采用此秘钥进行解密
        //converter.setSigningKey(SIGNING_KEY);

        //非对称解密进行签名令牌
        ClassPathResource classPathResource = new ClassPathResource("public-key.txt");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(classPathResource.getInputStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        converter.setVerifierKey(publicKey);

        return converter;
    }

    @Bean
    public TokenStore tokenStore() {
        //JWT管理令牌
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

}
